#include "audiospeaker.h"

#include <QDateTime>
#include <QDebug>
#include <QMutexLocker>

AudioSpeaker::AudioSpeaker(QObject *parent)
    : QThread{parent}, buffer_size_(0), queued_clock_(0.0) {}

AudioSpeaker::~AudioSpeaker() {}

void AudioSpeaker::Stop() { requestInterruption(); }

void AudioSpeaker::write(const char *data, int len, double clock) {

    AudioSpeakerFrame frame;
    frame.buf = data;
    frame.length = len;
    frame.clock = clock;

    QMutexLocker<QMutex> lock(&mutex_);
    queue_.enqueue(frame);
    cond_.notify_one();
}

void AudioSpeaker::run() {

    while (!isInterruptionRequested()) {
        mutex_.lock();
        qDebug() << QDateTime::currentDateTime() << QThread::currentThreadId()
                 << " wait ";
        while (queue_.empty() && !isInterruptionRequested()) {
            cond_.wait(&mutex_);
        }

        if (isInterruptionRequested()) {
            mutex_.unlock();
            break;
        }

        AudioSpeakerFrame frame_data = queue_.dequeue();
        mutex_.unlock();

        sleep(std::chrono::milliseconds(100));

        qDebug() << QDateTime::currentDateTime() << QThread::currentThreadId()
                 << " get " << frame_data.length;
    }

    qDebug() << "run finished ";
}
